from rest_framework import status
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from patient.models import PatientModel
from patient.serial import PatientSerializer
from rest_framework.viewsets import ModelViewSet

class PatientView(ModelViewSet):
    permission_classes = [IsAuthenticated]
    serializer_class = PatientSerializer

    def get_queryset(self):
        """
        获取当前登录用户的患者列表，只展示当前用户创建的患者信息
        """
        user = self.request.user  # 获取当前登录的用户
        return PatientModel.objects.filter(user_id=user.id).order_by('-id')

    def create(self, request, *args, **kwargs):
        data = request.data
        user = self.request.user  # 获取当前登录的用户
        print(data, "111111111111111111111111111111")
        print(user, "22222222222222222222222222222222222")

        data['user_id'] = user.id  # 为患者数据添加当前用户的 user_id
        print(data, "333333333333333333333333333333333333")

        serializer = self.get_serializer(data=data)

        # 检查序列化器是否有效
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "添加成功"}, status=status.HTTP_201_CREATED)
        else:
            # 如果序列化器无效，返回错误信息
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

    def update(self, request, pk=None, *args, **kwargs):
        """
        更新患者信息：只允许当前用户更新自己创建的患者信息
        """
        user = self.request.user  # 获取当前登录的用户
        try:
            patient = PatientModel.objects.get(id=pk)  # 查找患者
        except PatientModel.DoesNotExist:
            return Response({"detail": "患者不存在"}, status=status.HTTP_404_NOT_FOUND)

        # 如果患者不属于当前用户，则返回权限错误
        if patient.user_id != user.id:
            return Response({"detail": "你没有权限更新该患者信息"}, status=status.HTTP_403_FORBIDDEN)

        # 当前用户有权限更新，使用序列化器进行更新
        serializer = self.get_serializer(patient, data=request.data, partial=True)  # partial=True 允许部分更新
        if serializer.is_valid():
            serializer.save()
            return Response({"message": "更新成功"}, status=status.HTTP_200_OK)
        else:
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
